package com.apt.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.apt.common.AptException;
import com.apt.common.DBUtility;
import com.apt.domain.QuestionMaster;
import com.apt.domain.QuestionsAndOptions;
import com.apt.model.Option;
import com.apt.model.Question;

public class QuestionMasterDao extends BaseConnection {

	public QuestionMasterDao(Connection con) {
		super(con);
	}

	public List<Question> getQuestionsForTest(int testId) throws AptException {
		List<Question> questions = new ArrayList<Question>();
		List<QuestionMaster> qIds = new ArrayList<QuestionMaster>();
		try {

			PreparedStatement ps = connection
					.prepareStatement("SELECT QUESTION_ID,QUESTION from QUESTION_MASTER WHERE TEST_ID=?");
			ps.setInt(1, testId);
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {

				QuestionMaster qmaster = new QuestionMaster(rs.getInt(1),
						rs.getString(2));
				qIds.add(qmaster);

			}
			rs.close();
			//System.out.println("No Of Questions:" + qIds.size());
			ps = connection
					.prepareStatement("SELECT  A.QUESTION_ID,A.QUESTION,B.ANSWER_ID,B.ANSWER,B.ANSWER_CORRECT "
							+ "from QUESTION_MASTER A, ANSWER_MASTER B where A.QUESTION_ID = B.QUESTION_ID AND A.TEST_ID= ?");
			ps.setInt(1, testId);
			rs = ps.executeQuery();
			List<QuestionsAndOptions> questionsAndOptionsList = new ArrayList<QuestionsAndOptions>();
			while (rs.next()) {

				QuestionsAndOptions questionsAndOptions = new QuestionsAndOptions(
						rs.getInt(1), rs.getString(2), rs.getInt(3),
						rs.getString(4),rs.getString(5));
				questionsAndOptionsList.add(questionsAndOptions);

			}
			//System.out.println("Total rows:" + questionsAndOptionsList.size());

			for (QuestionMaster id : qIds) {

				List<Option> options = new ArrayList<Option>();
				boolean isCorrect = false;

				for (QuestionsAndOptions q : questionsAndOptionsList) {
					if (id.getQuestionId() == q.getQuestionId()) {
						
						if(q.getCorrectOption().equalsIgnoreCase("Y"))
						{
							isCorrect=true;
							
						}
						else
						{
							isCorrect=false;
							
						}
						Option opt = new Option(
								String.valueOf(q.getOptionId()), q.getOption(),isCorrect);
						options.add(opt);

					}

				}

				Question finalQ = new Question(String.valueOf(testId),
						String.valueOf(id.getQuestionId()), id.getQuestion(),
						options);
				questions.add(finalQ);

			}
			rs.close();
			//System.out.println("Total questions:" + questions.size());

		} catch (SQLException sqlEx) {
			sqlEx.printStackTrace();
			throw new AptException(
					"Unable to query the database to get the list of questions for the testId:"
							+ testId);

		} finally {
			DBUtility.cleanUp(connection);

		}

		return questions;

	}

}
